package com.xci.platform.auth.controller;

import com.xci.platform.auth.entity.HistoryEntity;
import com.xci.platform.auth.service.HistoryService;
import com.xci.platform.annotation.Authorize;
import com.xci.platform.core.BoolMessage;
import com.xci.platform.core.JsonGrid;
import com.xci.platform.helper.ExcelHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 系统历史记录控制器
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/auth/history")
public class HistoryController extends AuthBaseController {
    /**
     * 历史记录服务
     */
    @Resource
    protected HistoryService historyService;

    //region 页面视图

    /**
     * 历史记录首页
     */
    @GetMapping
    @Authorize(code = "SystemHistory")
    public String index() {
        return "auth/history/index";
    }

    /**
     * 历史记录详细页面
     */
    @GetMapping("/details")
    public String details(String id, ModelMap map) {
        HistoryEntity entity = historyService.queryById(id);
        if (entity == null) return notFound();
        map.put("entity", entity);
        return "auth/history/details";
    }

    //endregion

    //region 数据处理

    /**
     * 历史记录表格数据
     */
    @ResponseBody
    @GetMapping("/grid")
    @Authorize(code = "SystemHistory.Search")
    public JsonGrid grid(@RequestParam Map params) {
        return BoolMessage.grid(historyService.queryPage(params));
    }

    /**
     * 根据表名和主键查询历史记录分页列表
     */
    @ResponseBody
    @GetMapping("/gridbytable")
    public JsonGrid gridByTable(@RequestParam Map<String,String> params){
        String tableName = params.get("tableName");
        String keyValue= params.get("keyValue");
        return BoolMessage.grid(historyService.queryPageByTable(params));
    }

    /**
     * 导出历史记录
     */
    @GetMapping("/export")
    @Authorize(code = "SystemHistory.Export")
    public void export(@RequestParam Map params, HttpServletResponse response) throws IOException {
        ExcelHelper.exportWeb(response, historyService.export(params), HistoryEntity.class, "系统历史记录");
    }

    //endregion
}
